package com.ytd.smartcanteen.weighting.devices;

import android.util.Log;

import com.ytd.common.util.FormatUtil;
import com.ytd.common.util.LogUtil;
import com.ytd.smartcanteen.weighting.util.WeightConfig;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

import android_serialport_api.SerialCallback;
import android_serialport_api.SerialPort;

/**
 * 电子秤管理类
 *
 * @author gaoguanchao
 */
public class ScaleManager {
    private static final String TAG = "ScannerManager";

    private SerialPort mSerialPort = null;

    private boolean mInit;

    private ScaleCallBack mCallback;

    private BigDecimal mStableWeight = BigDecimal.ZERO;
    private BigDecimal mPeelWeight = BigDecimal.ZERO;
    private BigDecimal mChangeWeight = BigDecimal.ZERO;

    SerialCallback mSerialCallback = new SerialCallback() {
        @Override
        public void onReadData(final String data) {
            if (!mInit) {
                return;
            }
            if (data.contains("WGT")) {
//                LogUtil.d("onReadData:" + data);
                try {
                    String weightString = data.substring(data.indexOf(":") + 2, data.indexOf("P"));
                    BigDecimal bigDecimal = new BigDecimal(weightString.trim());
                    int adType = FormatUtil.parseInt(data.substring(data.indexOf(":") + 1, data.indexOf(":") + 2));
                    if ((adType & 1) == 1 && (mStableWeight.compareTo(bigDecimal) != 0)) {
                        int pIndex = data.indexOf("P");
                        if (pIndex != -1) {
                            mPeelWeight = new BigDecimal(data.substring(pIndex + 1, pIndex + 7).trim());
                        }
                        mStableWeight = bigDecimal;
                        if (mCallback != null) {
                            mCallback.onStable(mStableWeight);
                        }
                    }
                    if (mCallback != null && mChangeWeight.compareTo(bigDecimal) != 0) {
                        mChangeWeight = bigDecimal;
                        mCallback.onChange(bigDecimal);
                    }
                } catch (Exception e) {
                    LogUtil.e(TAG, "电子秤返回异常：" + data + "--" + Log.getStackTraceString(e));
                    release();
                    init();
                }
            } else {
                if (data.contains("RET")) {
                    LogUtil.d(TAG, "电子秤返回：" + data.trim());
                }
            }
        }
    };

    public void init() {
        try {
            String scalePath = WeightConfig.getScalePath();
            int scaleBit = WeightConfig.getScaleBit();
            LogUtil.d("ScaleManager init " + scalePath + "  " + scaleBit);
            mSerialPort = new SerialPort(new File(scalePath), scaleBit, mSerialCallback);
//            mSerialPort.tcflush();
            mInit = true;
            LogUtil.d("ScaleManager init success");
            mSerialPort.send("version\r\n".getBytes());
        } catch (IOException e) {
            LogUtil.e("ScaleManager init Exception", e);
            mInit = false;
        }
    }

    public BigDecimal getStableWeight() {
        return mStableWeight;
    }

    public BigDecimal getPeelWeight() {
        return mPeelWeight;
    }

    public void setCallback(ScaleCallBack callback) {
        mCallback = callback;
    }

    public void release() {
        mSerialPort.closePort();
        mSerialPort = null;
        mInit = false;
    }

    private ScaleManager() {
    }

    public static ScaleManager getInstance() {
        return ManagerHolder.instance;
    }

    public void zeroing() {
        if (mSerialPort != null) {
            mSerialPort.send("ZERO\r\n".getBytes());
        }
    }

    public void setPeel() {
//        YTARE（皮重）\r\n
        if (mSerialPort != null && mStableWeight != null) {
            double v = mStableWeight.add(mPeelWeight).doubleValue();
            mSerialPort.send(("YTARE" + v + "\r\n").getBytes());
        }
    }

    public void setAdSppeed(int start, int end) {
        if (mSerialPort != null) {
            mSerialPort.send(("SETADSPPEED " + start + " " + end + "\r\n").getBytes());
        }
    }

    private static class ManagerHolder {
        private static final ScaleManager instance = new ScaleManager();
    }

    public interface ScaleCallBack {
        void onStable(BigDecimal decimal);

        void onChange(BigDecimal decimal);
    }
}
